package util.jdbc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

/**
 * 数据库连接池管理类
 */
public class DBConnectionPool extends  Pool {

    private static final Logger logger = LoggerFactory.getLogger(DBConnectionPool.class);//日志
    private int checkedOut; //正在使用的连接数
    private Vector<Connection> freeConnections = new Vector<Connection>();//存放产生的连接对象容器
    private String password = null; //密码
    private String url = null; //连接数据库地址
    private String userName = null; //用户名
    private static  int num = 0;
    private static  int numActive = 0;
    private static  DBConnectionPool pool = null;  //连接池实例变量

    //产生数据库连接池
    public static synchronized  DBConnectionPool getInstance(){
        if(pool == null){
            pool = new DBConnectionPool();
        }
        return pool;
    }

    //获得一个数据库连接的实例
    private DBConnectionPool(){
        try {
            init();
            logger.error("开始初始化数据库连接，创建connection对象");
            for(int i=0;i<normalConnect;i++){//初始化normalConnect个连接
                Connection connection = newConnection();
                if(connection != null){
                    freeConnections.addElement(connection);//忘容器中添加一个连接对象
                    num++;//记录连接总数
                }
            }
            logger.error("初始化数据库连接完毕！");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //初始化
    private void init() throws IOException {
        logger.info("开始初始化数据库连接池" + new Date().toString());
        InputStream is = DBConnectionPool.class.getResourceAsStream(propertiesName);
        Properties p = new Properties();
        p.load(is);
        this.userName = p.getProperty("jdbc.username");
        this.password = p.getProperty("jdbc.password");
        this.driverName = p.getProperty("jdbc.driver");
        this.url = p.getProperty("jdbc.url");
        this.maxConnect = Integer.parseInt(p.getProperty("maxConnect"));
        this.normalConnect = Integer.parseInt(p.getProperty("normalConnect"));
        logger.info("初始化数据库连接池结束" + new Date().toString());
    }

    @Override
    public void createPool() {
        pool = new DBConnectionPool();
        if(pool != null){
            logger.info("创建连接池成功");
        }else {
            logger.error("创建连接池失败");
        }
    }

    //创建一个新的连接
    private Connection newConnection(){
        Connection connection = null;
        try {
            if(userName == null){
                connection = DriverManager.getConnection(url);
            }else {
                connection = DriverManager.getConnection(url,userName,password);
            }
            //logger.info("创建一个新连接");
        }catch (SQLException e){
            logger.info("无法创建这个url的连接" + url);
        }
        return connection;
    }
    @Override
    public Connection getConnection() {
        Connection connection = null;
        if(freeConnections.size()>0) {
            num--;
            connection = (Connection) freeConnections.firstElement();
            freeConnections.removeElement(0);

            try {
                if (connection.isClosed()) {
                    logger.info("从连接池中删除一个无效的连接");
                    connection = getConnection();
                }
            } catch (SQLException e) {
                logger.info("从连接池中删除一个无效连接");
                connection = getConnection();
            }
        }else if(maxConnect == 0 || checkedOut < maxConnect){//如果没有空闲连接且当前连接数小于最大空闲值，最大值为0则不限制
            connection = newConnection();
        }
        //当前连接数加1
        if(connection != null){
            checkedOut++;
        }
        numActive++;
        return connection;
    }

    @Override
    public synchronized Connection getConnection(Long time) {
        long startTime = new Date().getTime();
        Connection con;
        while ((con = getConnection()) == null){
            try {
                wait(time);//线程等待
            }catch (InterruptedException e){
            }
            if(new Date().getTime()  - startTime >= time){
                return  null;//如果超时则返回
            }
        }
        return null;
    }

    //如果不再使用某个连接对象，调用此方法将该对象释放到连接池
    @Override
    public void freeConnection(Connection connection) {
            freeConnections.addElement(connection);
            num++;
            checkedOut--;
            numActive--;
            notifyAll();//解锁
    }

    //返回当前空闲连接数
    @Override
    public int getNum() {
        return num;
    }

    //返回当前连接数
    @Override
    public int getNumActive() {
        return numActive;
    }

    public synchronized  void rlease(){
        try {
            Enumeration allConnections = freeConnections.elements();
            while (allConnections.hasMoreElements()){
                Connection connection = (Connection) allConnections.nextElement();
                try {
                    connection.close();
                    num--;
                }catch (SQLException e){
                    logger.info("无法关闭的连接");
                }
            }
            freeConnections.removeAllElements();
            numActive = 0;
        }finally {
            super.release();
        }
    }
}
